package com.woshua.processkeepmodel;

import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.annotation.Nullable;
import android.util.Log;
import android.widget.Toast;


/*
* Android进程间的通信   --- AIDL   --->>Binder进行使用
* */
public class LocalService extends Service {

    private MyBinder binder;

    private LocalConn localConn;

    @Override
    public void onCreate() {
        super.onCreate();

        binder=new MyBinder();

        if(localConn==null)
        {
            localConn=new LocalConn();
        }
    }


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        bindService(new Intent(LocalService.this,
                RemoteService.class),localConn, Context.BIND_IMPORTANT);
        return START_STICKY;
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return binder;
    }


    private class MyBinder extends IProcessAidlInterface.Stub
    {

        @Override
        public String getServiceName() throws RemoteException {
            return "local service";
        }
    }

    class LocalConn implements ServiceConnection
    {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.e("LocalService","远程进程已经启动。。。");

            IProcessAidlInterface aidlInterface = IProcessAidlInterface.Stub.asInterface(service);

            try {
                Log.i("LocalService", "connected with " + aidlInterface.getServiceName());
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
//            远程服务被干掉
            Toast.makeText(LocalService.this,"远程链接断开，重新启动 LocalService",Toast.LENGTH_LONG)
                    .show();

            startService(new Intent(LocalService.this,RemoteService.class));
            bindService(new Intent(LocalService.this,
                    RemoteService.class),localConn, Context.BIND_IMPORTANT);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        unbindService(localConn);
    }
}
